<template>
  <div class="point-box">
    <el-dialog
      ref="dialog"
      append-to-body
      :close-on-click-modal="false"
      :title="formTitle"
      fullscreen
      :visible.sync="dialogShow"
      width="1040px"
    >
      <br />
      <canvas
        ref="canvas"
        id="canvas"
        @mousemove="moveEvent"
        @click="getMousePos"
        class="map"
      ></canvas>
      {{ rangeValue }}
      <input
        type="range"
        id="scale-range"
        :min="rangeMin"
        :max="rangeMax"
        step="0.01"
        v-model="rangeValue"
        @mousemove="mousemoveCanvas()"
        style="display: block"
      />
      <div class="box">
        <el-switch v-model="pointType" active-text="点" inactive-text="区域"> </el-switch>
        <el-button @click="clearCanvas" style="margin-left: 20px" type="danger"
          >清除</el-button
        >
        <el-button @click="submit" style="float: right" type="primary">提交</el-button>
      </div>
      <!-- <img ref="img" :src="ycMapImg" @mousemove="moveEvent" @click="getMousePos" alt="" /> -->
    </el-dialog>
  </div>
</template>

<script>
import ycMapImg from "@/assets/images/yc.png";

export default {
  props: ["dialogShow", "formTitle"],
  data() {
    return {
      ycMapImg,
      pointType: true,
      // 表格数据项
      tableData: [],
      pointList: [],
      pointDomList: [],
      height: 0,
      rangeMin: 0.1,
      rangeMax: 1,
      rangeValue: 1.0,
      ctx: null,
      canvas: null,
      x: 0,
      y: 0,
      left: 0,
      img: null,
      canDraw: true,
    };
  },
  methods: {
    mousemoveCanvas() {
      // 在这里可以打印rangeValue的值
      let img = new Image();
      img.src = this.ycMapImg;
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.ctx.save();
      // alert(img.width);
      // this.ctx.translate(
      //   this.canvas.width / 2 - (img.width / 2) * this.rangeValue,
      //   this.canvas.height / 2 - (img.height / 2) * this.rangeValue
      // );
      this.ctx.scale(this.rangeValue, this.rangeValue);
      this.ctx.drawImage(img, 0, 0);
      this.ctx.restore();
    },
    add() {
      this.dialogShow = true;
      this.canDraw = true;
    },
    /*坐标转换*/
    windowToCanvas(x, y) {
      var box = canvas.getBoundingClientRect(); //这个方法返回一个矩形对象，包含四个属性：left、top、right和bottom。分别表示元素各边与页面上边和左边的距离
      return {
        x: x - box.left - (box.width - canvas.width) / 2,
        y: y - box.top - (box.height - canvas.height) / 2,
      };
    },
    getXY(canvas, evt) {
      let style = window.getComputedStyle(canvas, null);
      //宽高
      let cssWidth = parseFloat(style["width"]);
      let cssHeight = parseFloat(style["height"]);
      //各个方向的边框长度
      let borderLeft = parseFloat(style["border-left-width"]);
      let borderTop = parseFloat(style["border-top-width"]);
      let paddingLeft = parseFloat(style["padding-left"]);
      let paddingTop = parseFloat(style["padding-top"]);

      let scaleX = canvas.width / cssWidth; // 水平方向的缩放因子
      let scaleY = canvas.height / cssHeight; // 垂直方向的缩放因子

      let x = evt.clientX;
      let y = evt.clientY;

      let rect = canvas.getBoundingClientRect();
      x -= rect.left + borderLeft + paddingLeft; // 去除 borderLeft paddingLeft 后的坐标
      y -= rect.top + borderTop + paddingTop; // 去除 borderLeft paddingLeft 后的坐标

      x *= scaleX; // 修正水平方向的坐标
      y *= scaleY; // 修正垂直方向的坐标

      return { x, y };
    },
    getMousePos(event) {
      if (!this.canDraw) {
        return;
      }
      this.x = event.x - this.$refs.canvas.offsetLeft;
      this.y = event.y - this.$refs.canvas.offsetTop;

      if (!this.pointType) {
        this.drawDot(this.ctx, this.getXY(this.$refs.canvas, event));
        this.pointList.push(this.getXY(this.$refs.canvas, event));
        this.pointDomList.push({ x: this.x, y: this.y });
      } else {
        this.createCanvas();
        this.$nextTick(() => {
          setTimeout(() => {
            this.drawDot(this.ctx, this.getXY(this.$refs.canvas, event));
          }, 100);
        });
      }
    },
    moveEvent(event) {
      // console.log(this.$refs.dialog);
      // this.left = this.$refs.dialog.offsetLeft;
      // this.x = event.x;
      // this.y = event.y;
    },
    createCanvas() {
      this.$nextTick(() => {
        this.canvas = this.$refs.canvas;
        this.ctx = this.canvas.getContext("2d");
        let img = new Image();
        let that = this;
        img.src = this.ycMapImg;
        img.onload = function (e) {
          drawimg(img);
        };
        function drawimg(img) {
          that.ctx.clearRect(0, 0, that.canvas.width, that.canvas.height);
          that.ctx.drawImage(img, 0, 0, that.canvas.width, that.canvas.height);
        }
        document.getElementById("canvas").addEventListener("contextmenu", (event) => {
          event.preventDefault();
          if (this.pointType) {
            return;
          }
          if (this.pointList.length < 3) {
            console.log(this.$refs.canvas);
            that.$message.error("至少绘制3个点");
            return;
          }
          if (!this.canDraw) return;
          this.pointList.push(this.pointList[0]);
          this.pointDomList.push(this.pointDomList[0]);
          this.canDraw = false;
          this.$refs["canvas"] = null;
        });
        // ====
        // let imgScale = 1,
        //   imgX = 0,
        //   imgY = 0;
        // function drawImage() {
        //   that.ctx.clearRect(0, 0, that.$refs.canvas.width, that.$refs.canvas.height);
        //   that.ctx.drawImage(
        //     img, //规定要使用的图像、画布或视频。
        //     0,
        //     0, //开始剪切的 x 坐标位置。
        //     img.width,
        //     img.height, //被剪切图像的高度。
        //     imgX,
        //     imgY, //在画布上放置图像的 x 、y坐标位置。
        //     img.width * imgScale,
        //     img.height * imgScale //要使用的图像的宽度、高度
        //   );
        // }
        // that.$refs.canvas.onmousedown = function (event) {
        //   var pos = that.windowToCanvas(event.clientX, event.clientY); //坐标转换，将窗口坐标转换成canvas的坐标

        //   that.$refs.canvas.onmousemove = function (evt) {
        //     //移动
        //     canvas.style.cursor = "move";
        //     var posl = that.windowToCanvas(evt.clientX, evt.clientY);
        //     var x = posl.x - pos.x;
        //     var y = posl.y - pos.y;
        //     pos = posl;
        //     imgX = x;
        //     imgY = y;
        //     drawImage(); //重新绘制图片
        //   };
        //   canvas.onmouseup = function () {
        //     canvas.onmousemove = null;
        //     canvas.onmouseup = null;
        //     canvas.style.cursor = "default";
        //   };
        // };

        // this.$refs.canvas.onmousewheel = canvas.onwheel = function (event) {
        //   console.log(event);
        //   //滚轮放大缩小

        //   var pos = that.windowToCanvas(event.clientX, event.clientY);
        //   let wheelDelta = event.wheelDelta ? event.wheelDelta : event.deltalY * -40; //获取当前鼠标的滚动情况
        //   if (wheelDelta > 0) {
        //     imgScale *= 2;
        //     imgX = imgX * 2 - pos.x;
        //     imgY = imgY * 2 - pos.y;
        //   } else {
        //     imgScale /= 2;
        //     imgX = imgX * 0.5 - pos.x * 0.5;
        //     imgY = imgY * 0.5 - pos.y * 0.5;
        //   }
        //   drawImage(); //重新绘制图片
        // };
      });
    },
    draw(arr) {
      if (arr.length === 0) return;
      let that = this;
      that.ctx.beginPath();
      that.ctx.moveTo(arr[0].x, arr[0].y);

      that.ctx.stroke();
      that.ctx.beginPath();
      that.ctx.moveTo(arr[0].x, arr[0].y);

      for (var j = 0; j < arr.length; j++) {
        that.ctx.lineTo(arr[j].x, arr[j].y);
      }

      that.ctx.stroke();

      for (var k = 0; k < arr.length; k++) {
        console.log(arr[k]);
        // that.drawDot(that.ctx, arr[k], "red");
      }
    },
    drawDot(ctx1, pos, color) {
      console.log(this.ctx.arc);
      // let ctx = this.canvas.getContext("2d");
      this.ctx.beginPath();
      this.ctx.closePath();
      this.ctx.fill();
      this.ctx.arc(pos.x, pos.y, 4, 0 * Math.PI, 2 * Math.PI);
      this.ctx.fillStyle = "red";
      this.ctx.fill();
      this.ctx.stroke();
    },
    clearCanvas() {
      this.createCanvas();
      this.pointList = [];
      this.pointDomList = [];
      this.canDraw = true;
    },
    submit() {
      this.$emit("pointSubmit", {
        type: this.pointType ? "point" : "area",
        pointList: this.pointList,
        pointDomList: this.pointDomList,
        pos: this.pointType
          ? {
              x: this.x,
              y: this.y,
            }
          : null,
      });
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.height = document.body.clientHeight - 350;
    });
  },
  watch: {
    dialogShow(c, o) {
      if (!c) {
      } else {
        this.createCanvas();
      }
    },
    pointList(c, o) {
      if (c.length === 0) return;
      this.draw(c);
      let absX = Math.abs(c[0].x - c[c.length - 1].x);
      let absY = Math.abs(c[0].y - c[c.length - 1].y);
      if (absX < 5 && absY < 5) {
        c[c.length - 1] = c[0];
      }
    },
    pointType() {
      this.pointList = [];
      this.pointDomList = [];
      this.x = null;
      this.y = null;
      this.createCanvas();
      this.canDraw = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.point-box {
  padding: 20px;
}
.map {
  border: 1px solid #000;
  position: absolute;
  width: 1000px;
  height: 700px;
  left: 50%;
  margin-left: -500px;
}
.box {
  position: absolute;
  width: 1000px;
  left: 50%;
  margin-left: -500px;
  top: 780px;
}
.context-menu {
  position: absolute;
  z-index: 91199;
  background-color: rgba(240, 240, 240, 1);
  border-color: rgba(0, 0, 0, 0.4);
  border-style: solid;
  border-width: 1px;
  box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
  padding: 4px;
  position: fixed;
  width: 200px;
}
.context-menu-item {
  --height: 30px;
  cursor: pointer;
  height: var(--height);
  line-height: var(--height);
  list-style: none;
  padding-left: 5px;
  vertical-align: middle;
  transition-duration: 0.8s;
  transition-property: background-color;
  user-select: none;
}
.context-menu-item:hover {
  background-color: rgba(255, 255, 255, 1);
}
</style>
